//
//  GYSearchViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/6.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYSearchViewController.h"
#import "GYNetWorkTools.h"
#import "UIButton+GYExtension.h"
#import "GYSearchCell.h"
#import "GYSearchHeadView.h"
#import "NSString+FilePath.h"
#import "GYSearchResultViewController.h"

static NSString *cellIdentifier = @"cellIdentifier";
static NSString *sectionHeadIdentifier = @"sectionHeadIdentifier";
static NSString *sectionFootIdentifier = @"sectionFootIdentifier";
static NSString *historySearchWordPath = @"hotWord.plist";

@interface GYSearchViewController ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/** 热搜词清单 */
@property (nonatomic, strong) NSArray *hotSearchList;

/** 视图 */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 分区头视图 */
@property (nonatomic, strong) NSArray *sectionTitles;

/** 搜索框 */
@property (nonatomic, strong) UISearchBar *searchBar;

/** 缓存搜索的历史记录 */
@property (nonatomic, strong) NSMutableArray *cachesHotWords;

/** 当前搜索的内容 */
@property (nonatomic, strong) NSString *currentTitle;

//代表是前进还是返回
@property (nonatomic, getter=isState) BOOL state;
@end

@implementation GYSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
    
    //初始化collectionView
    [self setupCollectionView];
}

- (void)setupUI {
    self.view.backgroundColor = RGBColor(245, 245, 245);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(rightClick)];
    
    //设置搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 130, 40);
    searchBar.backgroundImage = [[UIImage alloc] init];
    UITextField *searchField = [searchBar valueForKey:@"searchField"];
    searchField.layer.borderColor = RGBColor(152, 152, 152).CGColor;
    searchField.textColor = RGBColor(0, 158, 214);
    searchBar.placeholder = @"请输入搜索关键词";
    self.navigationItem.titleView = searchBar;
    self.searchBar = searchBar;
    
    //加载热搜关键词
    [GYNetWorkTools requestHotSearch:^(NSDictionary *obj) {
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            self.hotSearchList = [datas objectForKey:@"list"];
            [self.collectionView reloadData];
        }
    } error:^(NSError *error) {
        NSLog(@"loadHotSearchFailed====%@",error);
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.state = NO;
    
    [self.searchBar resignFirstResponder];
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"GYSearchCell" bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    [collectionView registerNib:[UINib nibWithNibName:@"GYSearchHeadView" bundle:nil]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sectionHeadIdentifier];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:sectionFootIdentifier];
    
    //给collectionView添加点击手势
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
//    [collectionView addGestureRecognizer:tap];
}

- (void)rightClick {
    self.state = YES;
    [self.searchBar resignFirstResponder];
}

- (void)tap:(UITapGestureRecognizer *)tapGR {
    [self.searchBar resignFirstResponder];
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.hotSearchList.count;
    }else {
        return self.cachesHotWords.count;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.titleLable.text = self.hotSearchList[indexPath.item];
        cell.layer.cornerRadius = 15;
    }else {
        cell.titleLable.text = self.cachesHotWords[indexPath.item];
        cell.layer.cornerRadius = 0;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.state = YES;
    self.searchBar.text = indexPath.section == 0 ? self.hotSearchList[indexPath.item] : self.cachesHotWords[indexPath.row];
    
    if (indexPath.section == 0) {
        NSString *title = self.hotSearchList[indexPath.item];
        if (![self.cachesHotWords containsObject:title]) {
            self.searchBar.text = title;
            [self.cachesHotWords addObject:title];
            [collectionView reloadData];
            
            //1.要把历史记录存储在本地
            [self.cachesHotWords writeToFile:[NSString CachesDir:historySearchWordPath] atomically:YES];
        }
    }
    [self.searchBar resignFirstResponder];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GYSearchHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sectionHeadIdentifier forIndexPath:indexPath];
        headView.headTitleLable.text = self.sectionTitles[indexPath.section];
        
        return headView;
    }else {
        if (indexPath.section == 1) {
            UICollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:sectionFootIdentifier forIndexPath:indexPath];
            footView.backgroundColor = [UIColor clearColor];
            UIButton *btu = [UIButton buttonWithFrame:CGRectMake(50, 30, ScreenWidth-100, 44) title:@"清空历史" backgroundColor:RGBColor(238, 238, 238) fontSize:18 tag:1 target:self action:@selector(removeHistoryList)];
            [btu setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btu.layer.cornerRadius = 4;
            
            [footView addSubview:btu];
            
            return footView;
        }
        return nil;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(ScreenWidth, 30);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return CGSizeMake(ScreenWidth, 80);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        //collectionView如果要动态计算高度 不能使用indexPath来计算 会崩溃 要重新创建一个cell 来动态获取高度
        GYSearchCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"GYSearchCell" owner:nil options:nil] firstObject];
        
        return CGSizeMake([cell getWith], 30);
    }else {
        NSString *title = self.cachesHotWords[indexPath.item];
        CGFloat width = [title boundingRectWithSize:CGSizeMake(999, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size.width;
        return CGSizeMake(width+20, 30);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 10, 20, 10);
}

- (void)removeHistoryList {
    //1.清楚缓存
    [[NSFileManager defaultManager]removeItemAtPath:[NSString CachesDir:historySearchWordPath] error:nil];
    
    [self.cachesHotWords removeAllObjects];
    
    [self.collectionView reloadData];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}


#pragma mark -- UISearchBarDelegate 

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    //NSLog(@"结束编辑....");
    if (self.state) {
        if (searchBar.text.length != 0) {
            if (![self.cachesHotWords containsObject:searchBar.text]) {
                
                [self.cachesHotWords addObject:searchBar.text];
                [self.collectionView reloadData];
                
                //1.要把历史记录存储在本地
                [self.cachesHotWords writeToFile:[NSString CachesDir:historySearchWordPath] atomically:YES];
            }
        }
        //2.跳转到搜索结果界面
        GYSearchResultViewController *searchResultVC = [[GYSearchResultViewController alloc] init];
        searchResultVC.currentSearchTitle = searchBar.text;
        
        [self.navigationController pushViewController:searchResultVC animated:YES];
    }
}

//当店家键盘右下角的搜索按钮时候
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self rightClick];
}

#pragma mark -- 懒加载

- (NSArray *)sectionTitles {
    if (!_sectionTitles) {
        _sectionTitles = @[@"热门搜索",@"历史记录"];
    }
    return _sectionTitles;
}

- (NSMutableArray *)cachesHotWords {
    if (!_cachesHotWords) {
        _cachesHotWords = [NSMutableArray arrayWithContentsOfFile:[NSString CachesDir:historySearchWordPath]];
        if (_cachesHotWords == nil) {
            _cachesHotWords = [NSMutableArray array];
        }
    }
    
    return _cachesHotWords;
}


- (void)dealloc {
    NSLog(@"GYSearchViewController====dealloc");
}
@end
